package agend.client.behaviours;

import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.List;

import agend.client.gui.utils.Broker;
import agend.client.utils.GetAID;

import com.google.gdata.data.Person;
import com.google.gdata.data.calendar.CalendarEventEntry;

public class DeleteAppointmentBehaviour extends OneShotBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private CalendarEventEntry calendarEventEntry;
	
	public DeleteAppointmentBehaviour(CalendarEventEntry calendarEventEntry) {
		// TODO Auto-generated constructor stub
		this.calendarEventEntry = calendarEventEntry;
	}

	@Override
	public void action() {
		
		List<Person> persons = calendarEventEntry.getAuthors();
		
		int i=0; 
		while(i<persons.size() && !persons.get(i).getEmail().equals(myAgent.getLocalName().replace("#", "@")) )
			i++;
		
		if(i<persons.size())
		{
			Broker.getCalendarService().removeEvent(calendarEventEntry.getId());
		}
		else if(!persons.isEmpty())
		{
			ACLMessage aclMessage = new ACLMessage(ACLMessage.CANCEL);
			aclMessage.setSender(myAgent.getAID());
			aclMessage.addReceiver( GetAID.aid(myAgent.getLocalName()) );
			aclMessage.setConversationId("CLIENT-CANCEL-EVENT");
			
			String[] split = calendarEventEntry.getId().split("/");
			
			aclMessage.setContent( persons.get(0).getEmail().replace("@", "#")+"/-/"+split[split.length-1]);
			
			myAgent.send(aclMessage);
		}
	}
}
